package com.hxd.otc.dialog;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.flyco.dialog.widget.base.BaseDialog;
import com.hxd.otc.R;
import com.hxd.otc.base.BaseBean;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.common.enums.ExValidType;
import com.hxd.otc.module.my.activity.SecurityCenterActivity;
import com.hxd.otc.module.my.model.UserModel;
import com.hxd.otc.mvp.base.IBaseView;
import com.hxd.otc.net.BaseObserver;
import com.hxd.otc.utils.ResourceUtil;
import com.hxd.otc.utils.UIUtils;
import com.hxd.otc.widget.BlocksToast;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;

/**
 * 用户验证对应验证方式的验证码
 */
public class ConfirmValidTypeVerCodeDialog extends BaseDialog<ConfirmValidTypeVerCodeDialog> {
    private IBaseView mIView;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.et_ver_code)
    EditText mEtVerCode;
    @BindView(R.id.tv_send_ver_code)
    TextView mTvSendVerCode;

    private boolean mIsNoValidation;//是否确认时不进行验证码验证


    private OnExValidSuccessListener onExValidSuccessListener;
    private onGetVerCodeListener mOnGetVerCodeListener;

    public ConfirmValidTypeVerCodeDialog(Context context) {
        super(context);
        if (context instanceof IBaseView) {
            mIView = ((IBaseView) context);
        }
    }

    @Override
    public View onCreateView() {
        widthScale(0.67f);
        setCanceledOnTouchOutside(false);
        return View.inflate(getContext(), R.layout.dialog_ex_valid_type_input, null);
    }

    @Override
    public void onViewCreated(View view) {
        ButterKnife.bind(this, view);
    }

    @Override
    public void setUiBeforShow() {
        ExValidType exValidType = UserHelper.getExValidType();
        mEtVerCode.setText("");
        mTvTitle.setText(exValidType.getDesc());
        if (ExValidType.GoogleAuth.equals(exValidType)) {
            mEtVerCode.setHint(R.string.please_input_your_google_code);
            UIUtils.setGoogleCodeEditText(mEtVerCode);
        } else if (ExValidType.SMS.equals(exValidType)) {
            mEtVerCode.setHint(R.string.please_input_your_phone_ver_code);
            UIUtils.setPhoneVerCodeEditText(mEtVerCode);
//            sendPhoneSms();
        } else if (ExValidType.Email.equals(exValidType)) {
            mEtVerCode.setHint(R.string.please_input_your_email_ver_code);
            UIUtils.setEmailVerCodeEditText(mEtVerCode);
//            sendEmailVerCode();
        }
    }

    private void sendEmailVerCode() {
        UserModel.getInstance().sendExValidTypeEmail("ex_mail", new BaseObserver<String>() {
            @Override
            public void onNext(@NonNull String msg, @NonNull String s) {
                BlocksToast.get().showToast(R.string.email_ver_code_already_send_to_your_bound_email);
                startCountdown();
            }

            @Override
            public void onError(int errType, @NonNull String errMessage) {
                BlocksToast.get().showToast(errMessage);
            }
        }, mIView.<BaseBean<String>>bindAutoDispose());
    }

    private void sendPhoneSms() {
        UserModel.getInstance().sendExValidTypeMobileSms("ex_mobile", new BaseObserver<String>() {
            @Override
            public void onNext(@NonNull String msg, @NonNull String s) {
                BlocksToast.get().showToast(R.string.phone_sms_already_send_to_your_bound_phone);
                startCountdown();
            }

            @Override
            public void onError(int errType, @NonNull String errMessage) {
                BlocksToast.get().showToast(errMessage);
            }
        }, mIView.<BaseBean<String>>bindAutoDispose());
    }

    @Override
    public void show() {
        if (ExValidType.Other.equals(UserHelper.getExValidType())) {//还没设置验证方式
            showForbiddenBankCarDialog();
            dismiss();
            return;
        }
        super.show();
    }

    /**
     * 是否在点击确认时不进行验证码验证
     *
     * @param noValidation
     */
    public ConfirmValidTypeVerCodeDialog setNoValidation(boolean noValidation) {
        mIsNoValidation = noValidation;
        return this;
    }

    private void showForbiddenBankCarDialog() {
        new ForbiddenBankCardDialog<String>(getContext())
                .setMessage(ResourceUtil.getString(R.string.your_are_not_set_ex_valid_mode_should_go_to_security_center_set))
                .setData("")
                .setOnConfirmClickListener(new ForbiddenBankCardDialog.OnConfirmClickListener<String>() {
                    @Override
                    public void onConfirm(String data) {
                        Intent intent = new Intent(getContext(), SecurityCenterActivity.class);
                        getContext().startActivity(intent);
                    }
                }).show();

    }

    @Override
    public void show(int animStyle) {
        super.show(animStyle);
    }

    public ConfirmValidTypeVerCodeDialog setOnExValidTypeListener(OnExValidSuccessListener onExValidSuccessListener) {
        this.onExValidSuccessListener = onExValidSuccessListener;
        return this;
    }

    public ConfirmValidTypeVerCodeDialog setOnGetVerCodeListener(onGetVerCodeListener onGetVerCodeListener) {
        mOnGetVerCodeListener = onGetVerCodeListener;
        return this;
    }

    @OnClick({R.id.tv_cancel, R.id.tv_confirm, R.id.tv_send_ver_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_cancel:
                dismiss();
                break;
            case R.id.tv_confirm:
                onConfirm();
                break;
            case R.id.tv_send_ver_code:
                ExValidType exValidType = UserHelper.getExValidType();
                if (ExValidType.GoogleAuth.equals(exValidType)) {
                    UIUtils.setGoogleCodeEditText(mEtVerCode);
                } else if (ExValidType.SMS.equals(exValidType)) {
                    UIUtils.setPhoneVerCodeEditText(mEtVerCode);
                    sendPhoneSms();
                } else if (ExValidType.Email.equals(exValidType)) {
                    UIUtils.setEmailVerCodeEditText(mEtVerCode);
                    sendEmailVerCode();
                }
                break;
        }
    }

    private void onConfirm() {

        String verCode = mEtVerCode.getText().toString().trim();
        if (TextUtils.isEmpty(verCode)) {
            BlocksToast.get().showToast(mEtVerCode.getHint().toString());
            return;
        }

        if (mIsNoValidation) {
            if (mOnGetVerCodeListener != null) mOnGetVerCodeListener.onVerCode(verCode);
            dismiss();
            return;
        }


        UserModel.getInstance().validPayVerCode(verCode, new BaseObserver<String>() {
            @Override
            public void onNext(@NonNull String msg, @NonNull String s) {
                BlocksToast.get().showToast(R.string.verify_successfully);
                dismiss();
            }

            @Override
            public void onError(int errType, @NonNull String errMessage) {
                BlocksToast.get().showToast(errMessage);
            }
        }, mIView.<BaseBean<String>>bindAutoDispose());


        if (onExValidSuccessListener != null) {
            onExValidSuccessListener.onValidSuccess();
        }
        dismiss();
    }

    private Disposable mDisposable;

    /**
     * 开始倒计时
     */
    public void startCountdown() {
        //从0开始发射11个数字为：0-10依次输出，延时0s执行，每1s发射一次。
        mTvSendVerCode.setEnabled(false);
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
        mDisposable = Flowable.intervalRange(0, 60, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new io.reactivex.functions.Consumer<Long>() {
                    @SuppressLint("DefaultLocale")
                    @Override
                    public void accept(Long aLong) {
                        mTvSendVerCode.setText(String.format("%ds", 60 - aLong));
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() {
                        //倒计时完毕置为可点击状态
                        mTvSendVerCode.setEnabled(true);
                        mTvSendVerCode.setText(R.string.send_message_code);
                        if (mDisposable != null && !mDisposable.isDisposed()) {
                            mDisposable.dispose();
                            mDisposable = null;
                        }
                    }
                })
                .subscribe();
    }

    public interface OnExValidSuccessListener {
        void onValidSuccess();
    }

    public interface onGetVerCodeListener {
        void onVerCode(String verCode);
    }

    public interface OnVerCodeClickLinserter {
        void OnClick(String verCode);
    }

}
